﻿using IdentityServer4.Models;
using IdentityServer4.SqlSugarCore.DbContexts;
using IdentityServer4.SqlSugarCore.Interfaces;
using IdentityServer4.Stores;
using Microsoft.Extensions.Logging;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace IdentityServer4.SqlSugarCore
{
    public class ResourceStore : IResourceStore
    {
        private readonly ISqlSugarClient _db;

        public ResourceStore(DbContext dbContext)
        {
            _db = dbContext.Db;
        }

        public async Task<IEnumerable<ApiResource>> FindApiResourcesByNameAsync(IEnumerable<string> apiResourceNames)
        {
            var list = await _db.Queryable<Entities.ApiResource>().Where(x => apiResourceNames.Contains(x.Name) && x.Enabled).Select<ApiResource>().ToListAsync();
            return list;
        }

        public async Task<IEnumerable<ApiResource>> FindApiResourcesByScopeNameAsync(IEnumerable<string> scopeNames)
        {
            var list = await _db.Queryable<Entities.ApiResource, Entities.ApiScope>((x, o) => x.Name == o.Name)
                .Where((x, o) => scopeNames.Contains(o.Name) && x.Enabled)
                .Select<ApiResource>()
                .ToListAsync();
            return list;
        }

        public async Task<IEnumerable<ApiScope>> FindApiScopesByNameAsync(IEnumerable<string> scopeNames)
        {
            var list = await _db.Queryable<Entities.ApiScope>().Where(x => scopeNames.Contains(x.Name)).Select<ApiScope>().ToListAsync();
            return list;
        }

        public async Task<IEnumerable<IdentityResource>> FindIdentityResourcesByScopeNameAsync(IEnumerable<string> scopeNames)
        {
            var list = await _db.Queryable<Entities.IdentityResource>().Where(x => scopeNames.Contains(x.Name) && x.Enabled).Select<IdentityResource>().ToListAsync();
            return list;
        }

        /// <summary>
        /// 获取所有资源实现
        /// </summary>
        /// <returns></returns>
        public async Task<Resources> GetAllResourcesAsync()
        {
            var identityResourceData = await _db.Queryable<Entities.IdentityResource>().Where(x => x.Enabled).Select<IdentityResource>().ToListAsync();
            var apiResourceData = await _db.Queryable<Entities.ApiResource>().Where(x => x.Enabled).Select<ApiResource>().ToListAsync();
            var apiScopeData = await _db.Queryable<Entities.ApiScope>().Select<ApiScope>().ToListAsync();
            var model = new Resources(identityResourceData, apiResourceData, apiScopeData);
            return model;
        }
    }
}
